package li;

import org.junit.Before;
import org.junit.Test;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class Demo1 {
    Connection con;
    public static void main(String[] args)throws Exception {
        Class.forName("com.mysql.jdbc.Driver");
        String url = "jdbc:mysql://localhost:3306/a";
        String user = "root";
        String pass = "123";
        Connection con = DriverManager.getConnection(url, user, pass);
        Statement st = con.createStatement();

//        st.executeUpdate("insert into emp (name,sal) values('tom',4000)");
//        st.executeUpdate("delete from emp where id=6");
        String name = "'abc' or 1=1";//abc
        String p="hello";//123
        int sal = 4000;
//        int i = st.executeUpdate("update emp set dept_id=3 where name="+);
        ResultSet rs = st.executeQuery("select name,id from emp where name='"+name+"' and pass='"+p+"'");
        //where name='abc' or (1=1 and pass=hello)
        //select name,id from emp where name='a1' and sal=4000;
        while (rs.next()){
            System.out.println(rs.getObject("id")+" "+rs.getObject("name"));
        }
    }

    @Before
    public void init() throws Exception {
        Class.forName("com.mysql.jdbc.Driver");
        String url = "jdbc:mysql://localhost:3306/a";
        String user = "root";
        String pass = "123";
        con = DriverManager.getConnection(url, user, pass);
    }

    @Test
    public void m1()throws Exception{
        //安全，为什么安全？因为可以防止sql注入
        String sql = "insert into emp (name,sal) values(?,?)";
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setString(1,"admin");
        ps.setObject(2,5000);
        int i= ps.executeUpdate();
    }
    @Test
    public void m2()throws Exception{
        String sql = "delete from emp where id=?";
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setObject(1,7);
        int i= ps.executeUpdate();
    }
    @Test
    public void m3()throws Exception{
        String sql = "select * from emp where name=? and pass=?";
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setObject(1,"'abc' or 1=1");
        ResultSet rs = ps.executeQuery();
        List<Emp> list = new ArrayList<>();
        while (rs.next()){
            list.add(new Emp(rs.getInt("id"),rs.getString("name"),rs.getInt("sal")));
        }
        for (Emp emp : list) {
            System.out.println(emp);
        }
    }

}
